﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using Coolite.Ext.Web;
using Newtonsoft.Json.Linq;
using Pap.Services.WorkflowEngine;
using Pap.Web.Modules.Loan.ViewModel;
using Pap.Web.Utils;
using Utils;
using Utils.UIPermission;

namespace Pap.Web.Modules.Loan.Views
{
    /// <summary>
    /// 
    /// </summary>
    public partial class ReviewerWaitingList : BasePage<ReviewerWaitingListViewModel>, IPermittedPage
    {
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Ext.IsAjaxRequest && !Page.IsPostBack)
            {
                RefreshBoards();
                var actionList = from a in this.ViewModel.GetAvailableActions()
                                 where Enums.ToString(a) != Enums.ToString(ActionTypes.Return)
                                 select new
                                 {
                                     DecisionID = Enums.ToString(a),
                                     DecisionName = Enums.ToString(a, GetLocalResourceObject("LanguageIndex").ToInt32()),
                                 };
                storeDecisions.DataSource = actionList;
                storeDecisions.DataBind();
            }
        }

        /// <summary>
        /// Refreshes the boards.
        /// </summary>
        private void RefreshBoards()
        {
            IEnumerable boards = this.ViewModel.GetWaitingBoards();
            if (boards != null)
            {
                storeBoards.DataSource = boards;
                storeBoards.DataBind();

                RowSelectionModel selectionModel = grvBoards.SelectionModel.Primary as RowSelectionModel;
                selectionModel.ClearSelections();

                storeBoardLoans.RemoveAll();
            }
        }

        /// <summary>
        /// Handles the Selected event of the Boards gridview and get all its loans.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void Board_Selected(object sender, AjaxEventArgs e)
        {
            RowSelectionModel selectionModel = grvBoards.SelectionModel.Primary as RowSelectionModel;
            if (selectionModel.SelectedRows.Count > 0)
            {
                Guid boardId = new Guid(selectionModel.SelectedRows[0].RecordID);
                storeBoardLoans.DataSource = this.ViewModel.GetBoardLoans(boardId);
                storeBoardLoans.DataBind();
                ucAttachment.SetImages(this.ViewModel.GetBoardAttachements(boardId));
            }
            else storeBoardLoans.RemoveAll();
        }

        /// <summary>
        /// Handles the Clicked event of the BtnSave button that take a decision for loans discussed in a board.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void BtnSubmit_Clicked(object sender, AjaxEventArgs e)
        {
            try
            {
                RowSelectionModel selectionModel = grvBoards.SelectionModel.Primary as RowSelectionModel;
                if (selectionModel.SelectedRows.Count > 0)
                {
                    Guid boardID = (new Guid(selectionModel.SelectedRows[0].RecordID));
                    string jason = e.ExtraParams["grvBoards"];
                    JArray jarrChanges = (JArray)JSON.Deserialize(jason);
                    string boardNotes = jarrChanges[0]["StatusNotes"].ToString().Trim('"');

                    Dictionary<string, int> actionTypeDic = Enums.ToNameKeyPaires(typeof(ActionTypes));
                    jason = e.ExtraParams["grvBoardLoanGrid"];
                    jarrChanges = (JArray)JSON.Deserialize(jason);

                    var result = (from item in jarrChanges
                                  where (!string.IsNullOrEmpty(item["DecisionID"].ToString().Trim('"')))
                                  select new
                                             {
                                                 LoanID = item["LoanID"].ToString().Trim('"').ToGuid(),
                                                 Decision = (ActionTypes)actionTypeDic[item["DecisionID"].ToString().Trim('"')],
                                                 Notes = item["StatusNotes"].ToString().Trim('"'),
                                             });

                    if (result.Count() == jarrChanges.Count)
                    {
                        List<Guid> loansIds = new List<Guid>();
                        List<string> loansNotes = new List<string>();
                        List<ActionTypes> loansDecisions = new List<ActionTypes>();
                        foreach (var loan in result)
                        {
                            loansIds.Add(loan.LoanID);
                            loansNotes.Add(loan.Notes);
                            loansDecisions.Add(loan.Decision);
                        }

                        this.ViewModel.SubmitBoard(boardID, boardNotes, loansIds, loansNotes, loansDecisions);
                        RefreshBoards();
                    }
                    else
                    {
                        Ext.Msg.Configure(new MessageBox.Config
                        {
                            Icon = MessageBox.Icon.ERROR,
                            Title = GetLocalResourceObject("Error").ToString(),
                            Modal = true,
                            Message = GetLocalResourceObject("LoansNotSubmitted").ToString(),
                            Buttons = MessageBox.Button.OK
                        }).Show();
                    }
                }
                else
                {
                    Ext.Msg.Configure(new MessageBox.Config
                    {
                        Icon = MessageBox.Icon.ERROR,
                        Title = GetLocalResourceObject("Error").ToString(),
                        Modal = true,
                        Message = GetLocalResourceObject("NoSelectedBoards").ToString(),
                        Buttons = MessageBox.Button.OK
                    }).Show();
                }
            }
            catch
            {
                Ext.Msg.Configure(new MessageBox.Config
                {
                    Icon = MessageBox.Icon.ERROR,
                    Title = GetLocalResourceObject("Error").ToString(),
                    Modal = true,
                    Message = GetLocalResourceObject("ErrorMsg").ToString(),
                    Buttons = MessageBox.Button.OK
                }).Show();
            }
        }

        /// <summary>
        /// Handles the Clicked event of the btnReturn control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void btnReturn_Clicked(object sender, AjaxEventArgs e)
        {
            try
            {
                RowSelectionModel selectionModel = grvBoards.SelectionModel.Primary as RowSelectionModel;
                if (selectionModel.SelectedRows.Count > 0)
                {
                    Guid boardID = (new Guid(selectionModel.SelectedRows[0].RecordID));
                    string jason = e.ExtraParams["grvBoards"];
                    JArray jarrChanges = (JArray)JSON.Deserialize(jason);
                    string boardNotes = jarrChanges[0]["StatusNotes"].ToString().Trim('"');

                    this.ViewModel.ReturnBoard(boardID, boardNotes);
                    RefreshBoards();
                }
                else
                {
                    Ext.Msg.Configure(new MessageBox.Config
                    {
                        Icon = MessageBox.Icon.ERROR,
                        Title = GetLocalResourceObject("Error").ToString(),
                        Modal = true,
                        Message = GetLocalResourceObject("NoSelectedBoards").ToString(),
                        Buttons = MessageBox.Button.OK
                    }).Show();
                }
            }
            catch
            {
                Ext.Msg.Configure(new MessageBox.Config
                {
                    Icon = MessageBox.Icon.ERROR,
                    Title = GetLocalResourceObject("Error").ToString(),
                    Modal = true,
                    Message = GetLocalResourceObject("ErrorMsg").ToString(),
                    Buttons = MessageBox.Button.OK
                }).Show();
            }
        }

        /// <summary>
        /// Handles the Clicked event of the BtnCancle button.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void BtnCancle_Clicked(object sender, AjaxEventArgs e)
        {
            this.RedirectToPreviousPage();
        }


        /// <summary>
        /// Decisions the befor edit.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void DecisionBeforEdit(object sender, AjaxEventArgs e)
        {
            if (e.ExtraParams["ActionTypeID"] != null)
            {
                Guid actionTypeID = e.ExtraParams["ActionTypeID"].ToGuid();

                var actionList = from a in this.ViewModel.GetAvailableActions()
                                 where Enums.ToString(a) != Enums.ToString(ActionTypes.Return)
                                 select new
                                 {
                                     DecisionID = Enums.ToString(a),
                                     DecisionName = Enums.ToString(a, GetLocalResourceObject("LanguageIndex").ToInt32())
                                 };
                if (actionTypeID.Equals(Enums.ToString(ActionTypes.Refuse).ToGuid()))
                {
                    actionList = actionList.Where(aa => aa.DecisionID.ToGuid().Equals(Enums.ToString(ActionTypes.Refuse).ToGuid()));
                }
                if (actionTypeID.Equals(Enums.ToString(ActionTypes.FreezWithoutResearchAndStudy).ToGuid()) ||
                    actionTypeID.Equals(Enums.ToString(ActionTypes.FreezWithResearchAndStudy).ToGuid()))
                {
                    actionList = actionList.Where(aa =>
                        !aa.DecisionID.ToGuid().Equals(Enums.ToString(ActionTypes.Accept).ToGuid()) &&
                        !aa.DecisionID.ToGuid().Equals(Enums.ToString(ActionTypes.Refuse).ToGuid())
                        );
                }
                storeDecisions.DataSource = actionList;
                storeDecisions.DataBind();
            }
        }
        #region IPermittedPage Members

        /// <summary>
        /// Gets the name of the permission.
        /// </summary>
        /// <value>
        /// The name of the permission.
        /// </value>
        public string PermissionName
        {
            get { return "ReviewerWaitingList"; }
        }

        #endregion
    }
}
